package com.uplooking.controller;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.uplooking.pojo.Attendance;
import com.uplooking.pojo.JsonData;
import com.uplooking.pojo.User;
import com.uplooking.service.AttendanceService;
import com.uplooking.service.JmsSendEmailService;
import com.uplooking.service.UserService;
import com.uplooking.utils.AjaxReturn;
import com.uplooking.utils.JsonUtils;
import com.uplooking.utils.MyEmail;
import com.uplooking.utils.SimpleDateFormatUtil;

@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private AttendanceService attendanceService; 
	
	@Autowired
	private MyEmail MyEmail;
	
	@Autowired
    private JmsSendEmailService jmsSendEmailService;
    
    @Autowired
    @Qualifier("queueDestination")
    private Destination destination;
    
    @Resource(name="redisTemplate")
	private RedisTemplate redisTemplate;
	
	
	/**
	 * 用户登陆
	 * 用户打卡  
	 * @param user
	 * @param req
	 * @param resp
	 * @return
	 * @throws ParseException 
	 * @throws IOException 
	 */
	@RequestMapping("login")
	@ResponseBody
	public String login(User user,HttpServletRequest req,HttpServletResponse resp) throws ParseException{
		//默认打卡类型
		int type=1;
		
		AjaxReturn ajax =new AjaxReturn();
		
		User user2 = userService.login(user);
		if(user2!=null){
			req.getSession().setAttribute("user", user2);
			
			//现在的日期
			Date date = new Date();
			//设定打卡时间
			Date attendanceTime = SimpleDateFormatUtil.smt3.parse("09:05:00");
			//切割日   时
			String newDate = SimpleDateFormatUtil.smt1.format(date);
			String[] now = newDate.split(" ");
			//用现在时间跟打卡时间作比较
			Date nowTime = SimpleDateFormatUtil.smt3.parse(now[1]);
			if(nowTime.getTime()<=attendanceTime.getTime()){
				type=1;
			}else{
				type=2;
			}
			//查看用户是否第一次登陆
			Attendance attendance = userService.isFirst(user2,now[0]);
			if(attendance!=null){
				//如果是第一次就直接登陆
				ajax.setHead("ok");
				ajax.setBody("登陆成功！");
				return JsonUtils.objectToJson(ajax);
			}else{
				//如果不是第一次就将第一次打卡插入数据库
				Attendance attendance2=new Attendance();
					attendance2.setAttendanceTime(date);
					attendance2.setAttendanceDay(now[0]);
					attendance2.setAttendanceEvery(now[1]);
					attendance2.setAttendanceType(type);
					attendance2.setEmpid(user2.getUid());
				String result = attendanceService.insertAttendance(attendance2);
				System.out.println(result);
				
				ajax.setHead("ok");
				ajax.setBody("打卡成功！");
				return JsonUtils.objectToJson(ajax);
			}
		}else{
			ajax.setHead("error");
			ajax.setBody("用户名或者密码错误！");
			return JsonUtils.objectToJson(ajax);
		}
	}
	
	
	
	/**
	 * 退出登陆
	 * @param req
	 * @return
	 */
	@RequestMapping("logout")
	@ResponseBody
	public String logout(HttpServletRequest req) {
		AjaxReturn ajax =new AjaxReturn();
		//移出登陆状态
		req.getSession().removeAttribute("user");
		ajax.setHead("ok");
		ajax.setBody("退出成功");
		return JsonUtils.objectToJson(ajax);
	}
	
	
	/**
	 * 发送邮箱验证码
	 * @param req
	 * @return
	 */
	@RequestMapping("sendMail")
	@ResponseBody
	public String sendMail(String uname,String email,HttpServletRequest req) {
		AjaxReturn ajax =new AjaxReturn();
		
		//生成验证码
		MyEmail.setCode();
		String code = Integer.toString(MyEmail.getCode());
		redisTemplate.opsForValue().set(uname,code,60, TimeUnit.SECONDS);
		
		Map<String,Object> map = new HashMap<String, Object>();
        map.put("email", email);
        map.put("code", MyEmail.getCode());
        
        System.out.println("发送方发送内容为：" + JsonUtils.objectToJson(map));
        //ActiveMQ异步发送验证码 
        jmsSendEmailService.sendMessage(destination, JsonUtils.objectToJson(map));
		
		ajax.setHead("ok");
		ajax.setBody("发送成功");
		return JsonUtils.objectToJson(ajax);
		
	}
	
	
	/**
	  *  验证用户
	 * @param req
	 * @return
	 */
	@RequestMapping("checkUser")
	@ResponseBody
	public String checkUser(String uname,String email,int code,HttpServletRequest req) {
		AjaxReturn ajax =new AjaxReturn();
		
		//从缓存中获取验证码
		int redisCode=Integer.parseInt((String)redisTemplate.opsForValue().get(uname));
		
		//识别验证码
		if(redisCode!=code) {
			ajax.setHead("err");
			ajax.setBody("验证码错误");
			return JsonUtils.objectToJson(ajax);
		}
		//判断用户名跟邮箱是否匹配
		User user = userService.isMatch(uname,email);
		if(user!=null) {
			ajax.setHead("ok");
			ajax.setBody(user.getUid());
			ajax.setMsg("验证成功");
			return JsonUtils.objectToJson(ajax);
		}else {
			ajax.setHead("err");
			ajax.setMsg("用户名和邮箱不匹配");
			return JsonUtils.objectToJson(ajax);
		}
	}
	
	
	/**
	  *  修改密码
	 * @param req
	 * @return
	 */
	@RequestMapping("updatePwd")
	@ResponseBody
	public String updatePwd(String pwd,String repwd,int uid,HttpServletRequest req) {
		AjaxReturn ajax =new AjaxReturn();
		
		if(!pwd.equals(repwd)) {
			ajax.setHead("err");
			ajax.setMsg("密码与确认密码不匹配");
			return JsonUtils.objectToJson(ajax);
		}
		
		int result = userService.updatePwdById(uid,pwd);
		if(result==1) {
			ajax.setHead("ok");
			ajax.setMsg("修改成功");
			return JsonUtils.objectToJson(ajax);
		}else {
			ajax.setHead("err");
			ajax.setMsg("修改失败");
			return JsonUtils.objectToJson(ajax);
		}
	}
	
	/**
	 * 队员列表接口
	 * @param pageNum
	 * @param req
	 * @return
	 */
	@RequestMapping("team_list")
	public String team_list(@RequestParam(value="pageNum",defaultValue="1")int pageNum,@RequestParam(value="name",required=false)String name,HttpServletRequest req) {
		User user = (User) req.getSession().getAttribute("user");
		//System.out.println(user.getGid()+"  "+name);
		PageInfo userPageInfo = userService.findByGroup(user.getGid(), pageNum,name);
		
		req.setAttribute("name", name);
		req.setAttribute("userPageInfo", userPageInfo);
		return "team/team_list";
	}
	
	
	/**
	 * boss员工列表接口
	 * @param pageNum
	 * @param req
	 * @return
	 */
	@RequestMapping("boss_team_list")
	public String bossTeamList(@RequestParam(value="gid",defaultValue="1")int gid,@RequestParam(value="pageNum",defaultValue="1")int pageNum,@RequestParam(value="name",required=false)String name,HttpServletRequest req) {
		PageInfo userPageInfo = userService.findByGroup(gid, pageNum,name);
		
		req.setAttribute("name", name);
		req.setAttribute("gid", gid);
		req.setAttribute("userPageInfo", userPageInfo);
		return "team/bossTeam_list";
	}
	
	
	
	/**
	 * 添加队员
	 * @param pageNum
	 * @param req
	 * @return
	 */
	@RequestMapping("add_user")
	@ResponseBody
	public Object AddUser(User user,HttpServletRequest req) {
		AjaxReturn ajax =new AjaxReturn();
		
		int result = userService.insertUser(user);
		
		if(result==1) {
			ajax.setHead("ok");
			ajax.setMsg("新增成功");
		}else {
			ajax.setHead("err");
			ajax.setMsg("新增失败");
		}
		return JsonUtils.objectToJson(ajax);
	}
	
	
	/**
	 * 修改用户
	 * @param pageNum
	 * @param req
	 * @return
	 */
	@RequestMapping("update_user")
	@ResponseBody
	public Object updateUser(User user,HttpServletRequest req) {
		AjaxReturn ajax =new AjaxReturn();
		
		int result = userService.updateUser(user);
		if(result==1) {
			ajax.setHead("ok");
			ajax.setMsg("修改成功");
		}else {
			ajax.setHead("err");
			ajax.setMsg("修改失败");
		}
		return JsonUtils.objectToJson(ajax);
	}

}
